import book.Book;
import com.bit.utils.FileUtils;
import constant.Constant;
import utils.AnalyzingBook;

import java.io.IOException;

public class Library {
    public Book[] books;

    public int bookCount;



    public Library() {
        //调用该构造方法的时候，读取文件中的数据加载文件中的数据到books数组当中
        //默认数组容量给一个默认值
        //然后根据实际读取到的文件内容，来确定大小
        books = new Book[Constant.CAPACITY];

        loadBooks();
    }

    private void loadBooks() {
        try {
            Book[] allBooks = AnalyzingBook.loadObject(Constant.all_books_file);
            //当allBooks为空的时候进行处理，防止出现空指针异常
            if(allBooks == null) {
                bookCount = 0;
            }
            //判断allBooks的长度是否大于Books的初始长度
            if(allBooks.length > books.length) {
                //按照实际情况分配内存
                this.books = new Book[allBooks.length];
            }
            //把读到的元素进行赋值
            for (int i = 0; i < allBooks.length; i++) {
                this.books[i] = allBooks[i];
            }
            //修改实际有效书籍的个数
            bookCount = allBooks.length;
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    //将图书馆中的数据存储到文件之中，这个方法不希望在Library类之外的地方被调用
    private void storeObject(String filename) {
        try {
            AnalyzingBook.storeObject(books,filename);
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
}
